

# 终端执行  ruby shell_copy_file_to_framework.sh PPCommonUI

require "xcodeproj"
# 从终端接收参数
project_name = ARGV[0]
project_path = "./#{project_name}.xcodeproj"    # 工程的全路径
puts project_path
root_path = "Classes"
$target_name = "#{project_name}"
$project = Xcodeproj::Project.open("#{project_path}")

# 从工程中删除文件
$target = $project.targets.first

# 更新group（创建文件夹，并添加关联路径）
def update_group(path)
            $group = $project.main_group.find_subpath(File.join($target_name,path), true)
            $group.set_source_tree("<group>")
            $group.set_path(path)
            $group.set_source_tree("SOURCE_ROOT")
end

# 递归获取文件
def get_file_list(path)
    mPath = path;

  Dir.entries(path).each do |subpath|
    if subpath != "." && subpath != ".."
      if File.directory?("#{path}/#{subpath}")
        mPath = "#{path}/#{subpath}"
        update_group(mPath)
        get_file_list(mPath)
      else
      # 过滤掉隐藏文件
        if subpath.start_with?(".")
            next
        end
        
        if !subpath.end_with?(".h", ".m", ".mm", ".cpp")
            next
        end
        
#        puts "mPath = #{mPath}, path=#{path}, subpath=#{subpath}"
        # 递归过程，可能先进行子文件的扫描，返回上一级时，导致group还停留在子文件夹，
        # 因此需要判断一下，如果路径发生变化，则需要重新生成group
        if mPath != path
            mPath = path
            update_group(mPath)
        end
        file_ref = $group.new_reference(subpath)
        if file_ref.real_path.to_s.end_with?(".m", ".mm", ".cpp") then
            $target.source_build_phase.remove_file_reference(file_ref)
            $target.add_file_references([file_ref])
        elsif file_ref.real_path.to_s.end_with?(".h") then
                puts "mPath = #{mPath}, path=#{path}, subpath=#{subpath}"
            $target.headers_build_phase.remove_file_reference(file_ref)
            $target.add_file_references([file_ref])
        end
      end
    end
  end
end

# 将所有头文件添加到Public
def config_header_file_public
    $target.headers_build_phase.files.each do |build_file|
        build_file.settings = { "ATTRIBUTES" => ["Public"]}
    end
end

$group = $project.main_group.find_subpath(File.join($target_name, root_path), true)
if $group
    $group.clear()
    $group.groups.each do |group|
        puts group
        group.clear()
    end
end

#
get_file_list(root_path)

config_header_file_public

$group.set_source_tree("SOURCE_ROOT")

#工程目录排序
$project.sort()

#保存工程
$project.save

puts "文件添加完成"
